package servlet;

import dao.UserDAO;
import pojo.User;
import utils.ApiResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends BaseServlet {

    // 注册用户
    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String nickname = req.getParameter("nickname");
        String avatar = req.getParameter("avatar");
        String roleType = req.getParameter("roleType");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);
        user.setAvatar(avatar);
        user.setRoleType(roleType);
        user.setCreatedAt(LocalDateTime.now());
        try {
            if (UserDAO.usernameExists(username)) {
                sendJsonResponse(resp, new ApiResult(409, "用户名已存在", null)); // 409 Conflict
                return;
            }
            UserDAO.register(user);
            sendJsonResponse(resp, new ApiResult(200, "注册成功", null));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "注册失败", e.getMessage()));
        }
    }

    // 修改密码
    public void changePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");

        try {
            if (!UserDAO.checkOldPassword(username, oldPassword)) {
                sendJsonResponse(resp, new ApiResult(401, "旧密码错误", null)); // 401 Unauthorized
                return;
            }
            UserDAO.changePassword(username, newPassword);
            sendJsonResponse(resp, new ApiResult(200, "密码修改成功", null));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "修改密码失败", e.getMessage()));
        }
    }

    // 用户登录
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = UserDAO.login(username, password, req, resp);
        if (user != null) {
            // 将用户信息传递到前端
            req.setAttribute("user", user);
            req.getRequestDispatcher("/welcome.jsp").forward(req, resp);
        } else {
            resp.getWriter().println("用户名或密码错误");
        }
    }

    // 忘记密码，重置为默认密码000000
    public void resetPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        try {
            UserDAO.resetPassword(username);
            sendJsonResponse(resp, new ApiResult(200, "密码已重置为000000", null));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "重置密码失败", e.getMessage()));
        }
    }

    // 根据关键字分页模糊查询用户
    public void findByKeyword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String keyword = req.getParameter("keyword");
        int page = Integer.parseInt(req.getParameter("page"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));
        try {
            int count = UserDAO.getCountByKeyword(keyword);
            List<User> users = UserDAO.findByKeyword(keyword, page, pageSize);
            sendJsonResponse(resp, new ApiResult(200, "分页模糊查询用户成功", users, count));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "分页模糊查询用户失败", e.getMessage()));
        }
    }

    // 删除用户
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int userId = Integer.parseInt(req.getParameter("userId"));

        try {
            UserDAO.deleteUser(userId);
            sendJsonResponse(resp, new ApiResult(200, "用户删除成功", null));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "删除用户失败", e.getMessage()));
        }
    }

    // 更新用户
    public void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        int userId = Integer.parseInt(req.getParameter("userId"));
        String username = req.getParameter("username");
        String nickname = req.getParameter("nickname");
        String avatar = req.getParameter("avatar");
        String roleType = req.getParameter("roleType");

        User user = new User();
        user.setId(userId);
        user.setUsername(username);
        user.setNickname(nickname);
        user.setAvatar(avatar);
        user.setRoleType(roleType);
        user.setUpdatedAt(LocalDateTime.now());
        UserDAO.updateUser(user);
        sendJsonResponse(resp, new ApiResult(200, "用户更新成功", null));
    }

}
